package org.doubango.imsdroid.Login;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.doubango.imsdroid.R;
import org.doubango.imsdroid.Screens.BaseScreen;
import org.doubango.imsdroid.Screens.MainScreen;
import org.doubango.ngn.NgnEngine;
import org.doubango.ngn.services.INgnConfigurationService;
import org.doubango.ngn.services.INgnSipService;
import org.doubango.ngn.utils.NgnConfigurationEntry;
import org.json.JSONObject;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by TaZ on 2017/11/17.
 */

public class LoginActivity extends BaseScreen {

    private static String TAG = LoginActivity.class.getCanonicalName();
    private static String login_result = null;

    private final NgnEngine mEngine;
    private final INgnSipService mSipService;
    private final INgnConfigurationService mConfigurationService;

    private final static String SIP_DOMAIN = "59.110.217.175:9170";
    public static String SIP_USERNAME = null;
    private final static String SIP_PASSWORD = "654321";
    private final static String SIP_SERVER_HOST = "59.110.217.175";
    private final static int SIP_SERVER_PORT = 9170;

    private Button btn_reg;
    private Button btn_login;

    private final OkHttpClient client = new OkHttpClient();
    private EditText login_username;
    private EditText login_password;

    public LoginActivity() {
        super(SCREEN_TYPE.LOGIN_T, TAG);
        mEngine = NgnEngine.getInstance();
        mSipService = getEngine().getSipService();
        mConfigurationService = mEngine.getConfigurationService();
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                String json = (String) msg.obj;
                Log.i("Responsed", json);
                parseJSONWithJSONObject(json);
            }
            if(login_result == null) {
                Toast.makeText(LoginActivity.this, "万恶的后台DBA删库跑路了……", Toast.LENGTH_SHORT).show();

            } else if(login_result.equals("false")) {
                Toast.makeText(LoginActivity.this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
                login_username.setText("");
                login_password.setText("");
            } else if(login_result.equals("true")) {
                Toast.makeText(LoginActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                mScreenService.show(MainScreen.class);
//                Intent intent = new Intent(LoginActivity.this, MainScreen.class);
//                startActivity(intent);

                // Register
                if(mEngine.isStarted()) {
                    if(!mSipService.isRegistered()){
                        mConfigurationService.putString(NgnConfigurationEntry.IDENTITY_IMPI, SIP_USERNAME);
                        mConfigurationService.putString(NgnConfigurationEntry.IDENTITY_IMPU,
                                String.format("sip:%s@%s", SIP_USERNAME, SIP_DOMAIN));
                        mConfigurationService.putString(NgnConfigurationEntry.IDENTITY_PASSWORD, SIP_PASSWORD);
                        mConfigurationService.putString(NgnConfigurationEntry.NETWORK_PCSCF_HOST, SIP_SERVER_HOST);
                        mConfigurationService.putInt(NgnConfigurationEntry.NETWORK_PCSCF_PORT, SIP_SERVER_PORT);
                        mConfigurationService.putString(NgnConfigurationEntry.NETWORK_REALM, SIP_DOMAIN);
                        // VERY IMPORTANT: Commit changes
                        mConfigurationService.commit();
                        mSipService.register(LoginActivity.this);
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        btn_reg = (Button) findViewById(R.id.login_user);
        btn_login = (Button) findViewById(R.id.login_button);
        login_username = (EditText) findViewById(R.id.username);
        login_password = (EditText) findViewById(R.id.password);

        btn_reg.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                mScreenService.show(RegisterActivity.class);
//                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
//                startActivity(intent);
            }
        });

        //对登录按钮进行判断 如果符合条件 才可以登录
        btn_login.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                String user_name = login_username.getText().toString().trim();
                String user_pwd = login_password.getText().toString().trim();

                boolean result = isPassWord(user_pwd);

                if (user_name.length() == 0) {
                    Toast.makeText(LoginActivity.this, "用户名不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (result == false) {
                    Toast.makeText(LoginActivity.this, "请输入6-16位", Toast.LENGTH_SHORT).show();
                    return;
                }

                postRequest(user_name, user_pwd);
                Log.d("LoginActivity", "login_results is -------" +login_result);

            }
        });

    }

    /**
     * post请求后台
     *
     * @param name
     * @param pwd
     */
    private void postRequest(String name, String pwd) {

        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("userName", name)
                .add("loginPwd", pwd)
                .add("method", "okhttpreg")
                .build();

        //发起请求
        final Request request = new Request.Builder()
                .url("http://" + SIP_SERVER_HOST + ":8080/b/login.action?")
                .post(formBody)
                .build();

        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    String responseData = response.body().string();

                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, responseData).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //6-16位密码要求
    public static boolean isPassWord(String mobiles) {
        String telRegex = "^[0-9a-zA-Z]{6,16}$";
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }

    //{"remark":"1cdf913d8d354b689b74d57413d0c4e2","result":"login successful"}
    private void parseJSONWithJSONObject(String jsonData) {
        try {
            Log.d("LoginActivity", jsonData);

            JSONObject jsonObject = new JSONObject(jsonData);

            String remark = jsonObject.getString("remark");
            String results = jsonObject.getString("result");

            SIP_USERNAME = remark;
            login_result = results;

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
